import Vue from 'vue'
import VMain from './SnackBar.vue'

// 返回一个 扩展实例构造器
const SnackBarConstructor = Vue.extend(VMain)
const MySnackBarPlugin = {
  install: function(Vue, _globalOptions = {}) {
    function show(text, type, _options = {}) {
      const snackBarDom = new SnackBarConstructor({
        el: document.createElement('div'),
        propsData: {
          color: _options.color,
          type: type,
          text: text,
          x: _options.x,
          y: _options.y,
          mode: _options.mode,
          timeout: _options.timeout
        }
      })
      // 把 实例化的 toast.vue 添加到 body 里
      document.getElementById('app-wrap').appendChild(snackBarDom.$el)
      // document.body.appendChild(snackBarDom.$el)
    }
    // 添加实例属性
    Vue.prototype.$toasted = {
      info: function(text, options) {
        show(text, 'info', options)
      },
      success: function(text, options) {
        show(text, 'success', options)
      },
      error: function(text, options) {
        show(text, 'error', options)
      }
    }
  }
}
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(MySnackBarPlugin.install)
}
export default MySnackBarPlugin

// const SnackbarConstructor = Vue.extend(VMain)

// let instance
// let seed = 1
// const instances = []

// const Snackbar = (options) => {
//   let opts = options || {}
//   const id = `message_${seed += 1}`

//   if (typeof opts === 'string') {
//     opts = {
//       text: opts
//     }
//   }

//   instance = new SnackbarConstructor({
//     data: opts
//   })
//   instance.id = id
//   instance.vm = instance.$mount()
//   document.body.appendChild(instance.vm.$el)
//   instance.vm.visible = true
//   instance.dom = instance.vm.$el
//   instance.dom.style.zIndex = seed + 1001
//   instances.push(instance)
//   return instance.vm
// }

// ['success', 'warning', 'info', 'error'].forEach((type) => {
//   Snackbar[type] = (options) => {
//     let opts = options || {}

//     if (typeof opts === 'string') {
//       opts = {
//         text: opts
//       }
//     }

//     opts.type = type
//     return Snackbar(opts)
//   }
// })

// Snackbar.close = (id) => {
//   for (let i = 0, len = instances.length; i < len; i += 1) {
//     if (id === instances[i].id) {
//       instances.splice(i, 1)
//       break
//     }
//   }
// }

// /**
//  * can call Message.closeAll() to manually close all the instances.
//  */
// Snackbar.closeAll = () => {
//   for (let i = 0, len = instances.length; i < len; i += 1) {
//     instances[i].close()
//   }
// }

// export default Snackbar
